package com.rd.student.dashuju.zhengchengxiang.Test03;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class ThreadSum implements Runnable {
    private static volatile int totalSum = 0;
    private static final Lock lock = new ReentrantLock();
    private int startNumber;
    private int endNumber;

    public ThreadSum(int startNumber, int endNumber) {
        this.startNumber = startNumber;
        this.endNumber = endNumber;
    }

    @Override
    public void run() {
        int sum = 0;
        for (int i = startNumber; i <= endNumber; i++) {
            sum += i;
        }


        lock.lock();
        try {
            totalSum += sum;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Thread[] threads = new Thread[10];

        for (int i = 0; i < 10; i++) {
            int startNumber = i * 10 + 1;
            int endNumber = (i + 1) * 10;

            threads[i] = new Thread(new ThreadSum(startNumber, endNumber));
            threads[i].start();
        }

        // 等待所有线程执行完成
        try {
            for (Thread thread : threads) {
                thread.join();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("总和：" + totalSum);
    }
}



